package com.eastseeway.radioproject.engineer;


import android.widget.Toast;

import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.GridLayoutManager;

import com.eastseeway.radioproject.R;
import com.eastseeway.radioproject.base.BaseActivity;
import com.eastseeway.radioproject.base.Const;
import com.eastseeway.radioproject.databinding.ActivityEngineerBinding;
import com.eastseeway.radioproject.entities.Bean1FromHandle;
import com.eastseeway.radioproject.entities.BeanFromBottomBoard;
import com.eastseeway.radioproject.entities.BeanFromEnergyBoard;
import com.eastseeway.radioproject.entities.BeanFromNegativePressureBoard;
import com.eastseeway.radioproject.entities.BeanFromSwitchBoard;
import com.eastseeway.radioproject.entities.BeanOfVersionInfo;
import com.eastseeway.radioproject.entities.BottomBoardFunctionCode;
import com.eastseeway.radioproject.entities.MessageEvent;
import com.eastseeway.radioproject.utils.ByteUtil;
import com.eastseeway.radioproject.utils.CommandGenerator;
import com.eastseeway.radioproject.utils.SPHelper;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import struct.StructException;

public class EngineerActivity extends BaseActivity<ActivityEngineerBinding, EngineerViewModel> {

    private EngineerItemAdapter bottomBoardAdapter;
    private EngineerItemAdapter mNegativePressureAdapter;
    private EngineerItemAdapter mHandleAdapter;
    private EngineerItemAdapter mSwitchBoardAdapter;
    private EngineerItemAdapter mEnergyBoardAdapter;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_engineer;
    }
    @Override
    protected Class<EngineerViewModel> getVMClass() {
        return EngineerViewModel.class;
    }
    @Override
    protected void initEvent() {
        mBinding.setMViewModel(mViewModel);

        mBinding.back.setOnClickListener(v->finish());

//        底板部分
        mBinding.powerNegativeBoardCb.setOnCheckedChangeListener((buttonView, isChecked)->{
            try {
                byte[] command2BottomBoard = CommandGenerator.command2BottomBoard(Const.ADDRESS_TO_BOTTOM_BOARD, isChecked?BottomBoardFunctionCode.cmd_bottombrd_Power_On_Negative_Press_Board :BottomBoardFunctionCode.cmd_bottombrd_Power_Off_Negative_Press_Board, (short) 0);
                sendMessage(command2BottomBoard);
            } catch (StructException e) {
                throw new RuntimeException(e);
            }
        });

        try {
            sendMessage(CommandGenerator.commandRequestVersionInfo(Const.ADDRESS_VERSION_INFO_TO_SWITCH_BOARD));
            sendMessage(CommandGenerator.commandRequestVersionInfo(Const.ADDRESS_VERSION_INFO_TO_NEGATIVE_PRESSURE));
            sendMessage(CommandGenerator.command2BottomBoard(Const.ADDRESS_TO_BOTTOM_BOARD, BottomBoardFunctionCode.cmd_bottombrd_read_firmware_info, (short) 0));
        } catch (StructException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    protected void observeData() {
        mViewModel.getToastInfo().observe(this, s -> Toast.makeText(this, s, Toast.LENGTH_SHORT).show());

        mViewModel.is2MHz.observe(this, is2MHz -> {
            observeVBus();
        });
        mViewModel.isNegativePressureHandle.observe(this, isNegativePressureHandle -> {
            observeVBus();
        });

        mViewModel.getPressureBoardLiveData().observe(this, beanPressures -> {
            mNegativePressureAdapter.submitList(beanPressures);
        });
        mViewModel.getBottomBoardLiveData().observe(this, beanBoards -> {
            bottomBoardAdapter.submitList(beanBoards);
        });
        mViewModel.getHandleBoardLiveData().observe(this, beanHandles -> {
            mHandleAdapter.submitList(beanHandles);
        });
        mViewModel.getSwitchBoardData().observe(this, beanSwitchBoards -> {
            mSwitchBoardAdapter.submitList(beanSwitchBoards);
        });
        mViewModel.getEnergyBoardLiveData().observe(this, beanEnergyBoards -> {
            mEnergyBoardAdapter.submitList(beanEnergyBoards);
        });
    }

    private void observeVBus(){
//        mViewModel.queryVBusByHandleTypeAndFreq().observe(this, beanVBuses -> {
//            Log.e("12121","observeVBus "+new Gson().toJson(beanVBuses));
//            List<EngineerItemBean> beanVBusList = new ArrayList<>();
////            for (BeanVBus beanVBus : beanVBuses) {
////                beanVBusList.add(new EngineerItemBean(beanVBus.getTheoretical_value()+" ", beanVBus.getActual_value()));
////            }
////            mVBusAdapter.setData(beanVBusList);
//        });
    }

    @Override
    protected void loadData() {
        mBinding.switchBoardRv.setLayoutManager(new GridLayoutManager(this,2));
        mBinding.switchBoardRv.setItemAnimator(null);
        mBinding.switchBoardRv.setHasFixedSize(true);
        mSwitchBoardAdapter = new EngineerItemAdapter();
        mBinding.switchBoardRv.setAdapter(mSwitchBoardAdapter);

//        int requestPressure = SPHelper.getRequestPressure(this);
//        mViewModel.getHandlePressure().setValue(requestPressure+"");
        mBinding.negativePressureRv.setLayoutManager(new GridLayoutManager(this,2));
        mBinding.negativePressureRv.setItemAnimator(null);// 禁用动画提升性能
        mBinding.negativePressureRv.setHasFixedSize(true);// 固定尺寸优化
        mNegativePressureAdapter = new EngineerItemAdapter();
        mBinding.negativePressureRv.setAdapter(mNegativePressureAdapter);


        short vBusVoltage = SPHelper.getVBusVoltage(this);
        mViewModel.getVBusVoltage().setValue(vBusVoltage+"");
        mBinding.bottomRv.setLayoutManager(new GridLayoutManager(this,2));
        mBinding.bottomRv.setItemAnimator(new DefaultItemAnimator());
        bottomBoardAdapter = new EngineerItemAdapter();
        mBinding.bottomRv.setAdapter(bottomBoardAdapter);

        mBinding.handleRv.setLayoutManager(new GridLayoutManager(this,3));
        mBinding.handleRv.setItemAnimator(new DefaultItemAnimator());
        mHandleAdapter = new EngineerItemAdapter();
        mBinding.handleRv.setAdapter(mHandleAdapter);

        mBinding.energyBoardRv.setLayoutManager(new GridLayoutManager(this,3));
        mBinding.energyBoardRv.setItemAnimator(null);
        mBinding.energyBoardRv.setHasFixedSize(true);
        mEnergyBoardAdapter = new EngineerItemAdapter();
        mBinding.energyBoardRv.setAdapter(mEnergyBoardAdapter);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void OnEvent(MessageEvent messageEvent){
        if (messageEvent.getCode() == Const.ADDRESS_FROM_NEGATIVE_PRESSURE_BOARD) {
            BeanFromNegativePressureBoard beanFromNegativePressureBoard = (BeanFromNegativePressureBoard) messageEvent.getData();
            mViewModel.updatePressureData(beanFromNegativePressureBoard);
        }else if (messageEvent.getCode() == Const.ADDRESS_FROM_BOTTOM_BOARD){
            BeanFromBottomBoard beanFromBottomBoard = (BeanFromBottomBoard) messageEvent.getData();
            mBinding.powerNegativeBoardCb.setChecked((beanFromBottomBoard.getDev_status()>>5 & 1) == 1);
            mViewModel.updateBottomBoard(beanFromBottomBoard);
        }else if (messageEvent.getCode() == Const.ADDRESS_FROM_SWITCH_BOARD){//收到切换板信号
            BeanFromSwitchBoard beanFromSwitchBoard = (BeanFromSwitchBoard) messageEvent.getData();
//            初始化状态
            mBinding.switchBoardOnOff.setChecked(beanFromSwitchBoard.getDev_status() == 7);
            mViewModel.updateSwitchBoard(beanFromSwitchBoard);
        }else if(messageEvent.getCode() == Const.ADDRESS_FROM_ENERGY_BOARD){
            BeanFromEnergyBoard beanFromEnergyBoard = (BeanFromEnergyBoard) messageEvent.getData();
            mViewModel.updateEnergyBoard(beanFromEnergyBoard);
        } else if (messageEvent.getCode() == Const.ADDRESS_FROM_HANDLE_1_DATA_1) {
            if (mViewModel.getHasPressure().getValue()){
                Bean1FromHandle bean1FromHandle = (Bean1FromHandle) messageEvent.getData();
                mBinding.handleVersionInfo.setText(ByteUtil.convertByteArrayToASCIIString(bean1FromHandle.getBatch_production()) + "-" + ByteUtil.convertByteArrayToASCIIString(bean1FromHandle.getProduction_number()) + ByteUtil.convertByteArrayToASCIIString(bean1FromHandle.getElectrode_count()));
                mViewModel.updateHandleBoard(bean1FromHandle);
            }
        }else if(messageEvent.getCode() == Const.ADDRESS_FROM_HANDLE_2_DATA_1){
            if (!mViewModel.getHasPressure().getValue()){
                Bean1FromHandle bean1FromHandle = (Bean1FromHandle) messageEvent.getData();
                mBinding.handleVersionInfo.setText(ByteUtil.convertByteArrayToASCIIString(bean1FromHandle.getBatch_production())+"-"+ByteUtil.convertByteArrayToASCIIString(bean1FromHandle.getProduction_number())+ByteUtil.convertByteArrayToASCIIString(bean1FromHandle.getElectrode_count()));
                mViewModel.updateHandleBoard(bean1FromHandle);
            }
        }else if (messageEvent.getCode() == Const.ADDRESS_VERSION_INFO_FROM_NEGATIVE_PRESSURE){
            BeanOfVersionInfo beanOfVersionInfo = (BeanOfVersionInfo) messageEvent.getData();
            mBinding.pressureVersionInfo.setText("版本信息："+ByteUtil.convertByteArrayToASCIIString(beanOfVersionInfo.getSoftware_ver())+" -- "+ByteUtil.convertByteArrayToASCIIString(beanOfVersionInfo.getHardware_ver())+" -- "+ByteUtil.convertByteArrayToASCIIString(beanOfVersionInfo.getCompile_time()));
        }else if (messageEvent.getCode() == Const.ADDRESS_VERSION_INFO_FROM_BOTTOM_BOARD){
            BeanOfVersionInfo beanOfVersionInfo = (BeanOfVersionInfo) messageEvent.getData();
            mBinding.bottomBoardVersionInfo.setText("版本信息："+ByteUtil.convertByteArrayToASCIIString(beanOfVersionInfo.getSoftware_ver())+" -- "+ByteUtil.convertByteArrayToASCIIString(beanOfVersionInfo.getHardware_ver())+" -- "+ByteUtil.convertByteArrayToASCIIString(beanOfVersionInfo.getCompile_time()));
        }else if (messageEvent.getCode() == Const.ADDRESS_VERSION_INFO_FROM_SWITCH_BOARD){
            BeanOfVersionInfo beanOfVersionInfo = (BeanOfVersionInfo) messageEvent.getData();
            mBinding.switchBoardVersionInfo.setText("版本信息："+ByteUtil.convertByteArrayToASCIIString(beanOfVersionInfo.getSoftware_ver())+" -- "+ByteUtil.convertByteArrayToASCIIString(beanOfVersionInfo.getHardware_ver())+" -- "+ByteUtil.convertByteArrayToASCIIString(beanOfVersionInfo.getCompile_time()));
        }
    }

}
